from django.shortcuts import render

# Create your views here.
# core/views.py
from django.shortcuts import render, get_object_or_404
from .models import TrashItem, Article
from django.db.models import Q

from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from .models import SearchHistory
from django.http import HttpResponseRedirect
from django.urls import reverse
from .models import Favorite
from django.contrib.auth import logout
def home(request):
    return render(request, 'core/home.html')

def search(request):
    keyword = request.GET.get('q', '')
    results = []

    if keyword:
        results = TrashItem.objects.filter(name__icontains=keyword)

        # 如果用户已登录，则保存搜索记录
        if request.user.is_authenticated:
            SearchHistory.objects.create(user=request.user, keyword=keyword)

    return render(request, 'core/search.html', {
        'results': results,
        'keyword': keyword
    })
def trash_detail(request, item_id):
    item = get_object_or_404(TrashItem, pk=item_id)
    return render(request, 'core/detail.html', {'item': item})




def register(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            user = form.save()
            login(request, user)  # 注册成功自动登录
            return redirect('home')
    else:
        form = UserCreationForm()
    return render(request, 'core/register.html', {'form': form})



def user_logout(request):
    logout(request)
    return redirect('login')  # 修改为你想跳转的页面



@login_required
def my_history(request):
    history = SearchHistory.objects.filter(user=request.user).order_by('-searched_at')
    return render(request, 'core/my_history.html', {'history': history})





@login_required
def toggle_favorite(request, item_id):
    item = TrashItem.objects.get(id=item_id)
    favorite, created = Favorite.objects.get_or_create(user=request.user, trash_item=item)

    if not created:
        favorite.delete()  # 如果已经收藏，就取消收藏

    return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('home')))


@login_required
def my_favorites(request):
    favorites = Favorite.objects.filter(user=request.user).select_related('trash_item')
    return render(request, 'core/my_favorites.html', {'favorites': favorites})



def article_list(request):
    articles = Article.objects.all().order_by('-created_at')
    return render(request, 'core/article_list.html', {'articles': articles})

def article_detail(request, article_id):
    article = Article.objects.get(id=article_id)
    return render(request, 'core/article_detail.html', {'article': article})
